package com.live.shop.home;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.PowerManager;
import android.provider.Settings;
import android.view.KeyEvent;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;

import com.bumptech.glide.Glide;
import com.live.shop.BaseActivity;
import com.live.shop.R;
import com.live.shop.home.setting.PermissionActivity;
import com.live.shop.home.setting.SettingActivity;
import com.live.shop.model.UserModel;
import com.live.shop.scene.server.WsHomeServerActivity;
import com.live.shop.service.SuspendedWindowService;
import com.live.shop.service.TokenService;
import com.live.shop.sql.KeywordListDatabase;
import com.live.shop.sql.PrologueListDatabase;
import com.live.shop.sql.UserDatabase;
import com.live.shop.tool.CrashHandler;
import com.live.shop.tool.GetUtil;
import com.live.shop.tool.OkHttpUtils;
import com.live.shop.tool.StatusBarUtils;
import com.live.shop.tool.UpdateChecker;
import com.live.shop.view.ToastBottomUtils;
import com.live.shop.view.XCRoundImageView;

import org.json.JSONObject;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Response;

public class HomeActivity extends BaseActivity {
    RelativeLayout home_function;
    RelativeLayout home_window;
    RelativeLayout home_prologue;
    RelativeLayout home_keyword;
    RelativeLayout home_music;
    RelativeLayout home_comment;
    RelativeLayout home_screen;
    RelativeLayout home_setting;

    XCRoundImageView home_user_headurl;
    TextView home_user_nickname;
    TextView home_user_account;
    TextView home_endtime;
    TextView home_window_status;
    TextView home_prologue_num;
    TextView home_prologue_use_num;
    TextView home_keyword_num;
    TextView home_keyword_use_num;
    int Function_id;
    UserDatabase userDb;
    UserModel userModel;
    private long exitTime = 0;
    private PowerManager.WakeLock wakeLock = null;


    @SuppressLint("MissingInflatedId")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);
        StatusBarUtils.setStatusBarDarkMode(getWindow(),R.color.home_bg);

        home_function = findViewById(R.id.home_function);
        home_window = findViewById(R.id.home_window);
        home_prologue = findViewById(R.id.home_prologue);
        home_keyword = findViewById(R.id.home_keyword);
        home_music = findViewById(R.id.home_music);
        home_comment = findViewById(R.id.home_comment);
        home_screen = findViewById(R.id.home_screen);
        home_setting = findViewById(R.id.home_setting);

        home_user_headurl = findViewById(R.id.home_user_headurl);
        home_user_nickname = findViewById(R.id.home_user_nickname);
        home_user_account = findViewById(R.id.home_user_account);
        home_endtime = findViewById(R.id.home_endtime);
        home_window_status = findViewById(R.id.home_window_status);
        home_prologue_num = findViewById(R.id.home_prologue_num);
        home_prologue_use_num = findViewById(R.id.home_prologue_use_num);
        home_keyword_num = findViewById(R.id.home_keyword_num);
        home_keyword_use_num = findViewById(R.id.home_keyword_use_num);
        userDb =new UserDatabase(getApplicationContext());
        userModel = userDb.select();
        init();
        //检查更新
        new UpdateChecker(HomeActivity.this,false).checkForUpdates();
        //获取异常日志
        CrashHandler.getInstance().init(this,userModel.getToken());
        //初始化锁
        acquireWakeLock();
    }
    //获取锁
    private void acquireWakeLock() {
        if(wakeLock == null) {
            // 获取电源管理器
            PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
            // 设置 WakeLock
            wakeLock = powerManager.newWakeLock(PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP, "MyApp:WakeLockTag");
            // 保持屏幕常亮
            getWindow().addFlags(android.view.WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        }
    }

    @SuppressLint("UnspecifiedRegisterReceiverFlag")
    private void init(){
        home_function.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(getApplicationContext(),FunctionsActivity.class));
            }
        });
        home_window.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(!Settings.canDrawOverlays(getApplicationContext())){
                    startActivity(new Intent(getApplicationContext(), PermissionActivity.class));
                    ToastBottomUtils.Setinfo(getApplicationContext(),"请到设置中授权【悬浮窗】权限！");
                    return;
                }
                //快手和淘宝 其他需要开启无障碍
                if ((Function_id == 1 || Function_id == 2 || Function_id == 4 || Function_id == 5 || Function_id == 7 || Function_id == 8)
                        && !GetUtil.isAccessibilitySettingsOn(getApplicationContext())) {
                    Intent intent3 = new Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS);
                    intent3.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(intent3);
                    ToastBottomUtils.Setinfo(getApplicationContext(),"请授权【无障碍】权限！");
                    return;
                }
                if(Function_id == 0){
                    ToastBottomUtils.Setinfo(getApplicationContext(),"请先选择【应用平台】！");
                    return;
                }

                if(GetUtil.isServiceWork(getApplicationContext(),getPackageName()+".service.SuspendedWindowService")){
                    home_window_status.setText("已关闭");
                    home_window_status.setTextColor(getColor(R.color.red));
                    stopService(new Intent(getApplicationContext(), SuspendedWindowService.class));
                    ToastBottomUtils.Setinfo(getApplicationContext(),"已关闭服务");

                    setNum();//设置数值
                }else{
                    home_window_status.setText("已开启");
                    home_window_status.setTextColor(getColor(R.color.blue));
                    //打开悬浮窗服务
                    startService(new Intent(getApplicationContext(), SuspendedWindowService.class));
                    try {
                        //提交使用量
                        JSONObject setJson = new JSONObject();
                        setJson.put("function_id",Function_id);
                        getAccount(GetUtil.setAppUse(),setJson.toString(),userModel.getToken());
                    }catch (Exception e){
                        e.printStackTrace();
                    }

                    ToastBottomUtils.Setinfo(getApplicationContext(),"已开启服务");
                }
            }
        });
        home_prologue.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
                    //读写(高版本)
                    if(!Environment.isExternalStorageManager()){
                        ToastBottomUtils.Setinfo(getApplicationContext(),"请到设置中授权【读写】权限！");
                        startActivity(new Intent(getApplicationContext(), PermissionActivity.class));
                        return;
                    }
                }else{
                    //低版本
                    if(ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED ||
                            ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED){
                        ToastBottomUtils.Setinfo(getApplicationContext(),"请到设置中授权【读写】权限！");
                        startActivity(new Intent(getApplicationContext(), PermissionActivity.class));
                        return;
                    }
                }
                startActivity(new Intent(getApplicationContext(), ProloguesListActivity.class));
            }
        });
        home_keyword.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
                    //读写(高版本)
                    if(!Environment.isExternalStorageManager()){
                        ToastBottomUtils.Setinfo(getApplicationContext(),"请到设置中授权【读写】权限！");
                        startActivity(new Intent(getApplicationContext(), PermissionActivity.class));
                        return;
                    }
                }else{
                    //低版本
                    if(ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED ||
                            ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED){
                        ToastBottomUtils.Setinfo(getApplicationContext(),"请到设置中授权【读写】权限！");
                        startActivity(new Intent(getApplicationContext(), PermissionActivity.class));
                        return;
                    }
                }
                startActivity(new Intent(getApplicationContext(), KeywordsListActivity.class));
            }
        });
        home_music.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
                    //读写(高版本)
                    if(!Environment.isExternalStorageManager()){
                        ToastBottomUtils.Setinfo(getApplicationContext(),"请到设置中授权【读写】权限！");
                        startActivity(new Intent(getApplicationContext(), PermissionActivity.class));
                        return;
                    }
                }else{
                    //低版本
                    if(ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED ||
                            ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED){
                        ToastBottomUtils.Setinfo(getApplicationContext(),"请到设置中授权【读写】权限！");
                        startActivity(new Intent(getApplicationContext(), PermissionActivity.class));
                        return;
                    }
                }
                startActivity(new Intent(getApplicationContext(),MusicListActivity.class));
            }
        });
        home_screen.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
                    //读写(高版本)
                    if(!Environment.isExternalStorageManager()){
                        ToastBottomUtils.Setinfo(getApplicationContext(),"请到设置中授权【读写】权限！");
                        startActivity(new Intent(getApplicationContext(), PermissionActivity.class));
                        return;
                    }
                }else{
                    //低版本
                    if(ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED ||
                            ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED){
                        ToastBottomUtils.Setinfo(getApplicationContext(),"请到设置中授权【读写】权限！");
                        startActivity(new Intent(getApplicationContext(), PermissionActivity.class));
                        return;
                    }
                }
                WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
                if (wifiManager.isWifiEnabled()){
                    startActivity(new Intent(getApplicationContext(), WsHomeServerActivity.class));
                }else{
                    ToastBottomUtils.Setinfo(getApplicationContext(),"未连接WIFI");
                }
            }
        });
        home_setting.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(getApplicationContext(), SettingActivity.class));
            }
        });
        home_comment.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(getApplicationContext(), LiveCommentsActivity.class));
            }
        });
        //注册广播接收器
        IntentFilter intentFilter = new IntentFilter("HomeActivityStatus");
        registerReceiver(broadcastReceiver, intentFilter);
    }
    //设置数值
    private void setNum(){
        KeywordListDatabase keyDb = new KeywordListDatabase(getApplicationContext());
        PrologueListDatabase proDb = new PrologueListDatabase(getApplicationContext());
        String[] keyword = keyDb.selectNum();
        home_keyword_num.setText(keyword[0]);
        home_keyword_use_num.setText(keyword[1]);

        String[] prologue = proDb.selectNum();
        home_prologue_num.setText(prologue[0]);
        home_prologue_use_num.setText(prologue[1]);
    }
    //广播接收
    private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
        @SuppressLint("SetTextI18n")
        @Override
        public void onReceive(Context context, Intent intent) {
            //接收到悬浮窗关闭
            if(intent.hasExtra("window_status")){
                String data = intent.getStringExtra("window_status");
                if(data != null && data.equals("close")){
                    home_window_status.setText("已关闭");
                    home_window_status.setTextColor(getColor(R.color.red));
                    setNum();//设置数值
                }
            }
        }
    };
    //设置悬浮窗状态
    private void getWindowStatus(){
        boolean iswork = GetUtil.isServiceWork(getApplicationContext(),getPackageName()+".service.SuspendedWindowService");
        if(iswork){
            home_window_status.setText("已开启");
            home_window_status.setTextColor(getColor(R.color.blue));
        }else{
            home_window_status.setText("已关闭");
            home_window_status.setTextColor(getColor(R.color.red));
        }
    }
    //启用Token服务
    private void getTokenStatus(){
        boolean iswork = GetUtil.isServiceWork(getApplicationContext(),getPackageName()+".service.TokenService");
        if(!iswork){
            startService(new Intent(getApplicationContext(), TokenService.class));
        }
    }
    //设置账户
    public void setUserInfo(){
        userModel = userDb.select();
        Function_id = userModel.getFunctionId();
        home_user_nickname.setText("昵称："+userModel.getNickname());
        home_user_account.setText("账户："+userModel.getAccount());
        home_endtime.setText("会员截至："+userModel.getEndtime());
        if(userModel.getHeadurl() != null && !userModel.getHeadurl().isEmpty()){
            Uri uri = Uri.parse(userModel.getHeadurl());
            Glide.with(this).load(uri).into(home_user_headurl);
        }
    }
    @Override
    protected void onResume() {
        //在Activity已可见，获取焦点开始与用户交互时调用；
        super.onResume();
        getTokenStatus();//token服务
        setUserInfo();//设置账户
        getWindowStatus();//设置悬浮窗状态
        setNum();//设置数值
        // 获取锁
        wakeLock.acquire();
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        //取消注册广播接收器
        if(broadcastReceiver != null){
            unregisterReceiver(broadcastReceiver);
            broadcastReceiver = null;
        }
        //释放锁
        if (wakeLock != null) {
            wakeLock.release();
        }
        stopService(new Intent(getApplicationContext(), TokenService.class));
    }
    public void getAccount(String url,String jsonStr,String token){
        OkHttpUtils.sendOkHttpJsonTokenRequest(url, jsonStr,new okhttp3.Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {

            }
            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {}
        },token);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {           // 判断2次点击事件时间
            if ((System.currentTimeMillis() - exitTime) > 2000) {
                ToastBottomUtils.Setinfo(getApplicationContext(),"再按一次退出程序");
                exitTime = System.currentTimeMillis();
            } else {
                finish();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}